package mysession

import (
	"fmt"
	"net/http"
	"reflect"

	"github.com/astaxie/session"
	_ "github.com/astaxie/session/providers/memory"
)

var globalSessions *session.Manager
var IsLogin int = 0

type GURL struct {
	Iw http.ResponseWriter

	Ir *http.Request
}

var GGurl GURL

func SetHttpparams(w http.ResponseWriter, r *http.Request) {
	GGurl.Iw = w
	GGurl.Ir = r

}

func CheckLogin(w http.ResponseWriter, r *http.Request) {
	if Sessionget("username") == nil {

		fmt.Fprint(w, "<script>location.href='https://www.baidu.com';</script>")
	}
}

func Sessionset(name string, value string) {

	globalSessions, _ = session.NewManager("memory", "gosessionid", 3600)
	go globalSessions.GC()

	sess := globalSessions.SessionStart(GGurl.Iw, GGurl.Ir)
	sess.Set(name, value)
}

func Sessionget(name string) interface{} {

	globalSessions, _ = session.NewManager("memory", "gosessionid", 3600)
	go globalSessions.GC()

	sess := globalSessions.SessionStart(GGurl.Iw, GGurl.Ir)

	return sess.Get(name)

}

func In(haystack interface{}, needle interface{}) (bool, error) {
	sVal := reflect.ValueOf(haystack)
	kind := sVal.Kind()
	if kind == reflect.Slice || kind == reflect.Array {
		for i := 0; i < sVal.Len(); i++ {
			if sVal.Index(i).Interface() == needle {
				return true, nil
			}
		}

		return false, nil
	}

	return false, nil
}
